package com.csist.util;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;

import java.util.Date;
import java.util.UUID;

public class JwtUtil {
    //过期时间
    @Value("${jwt.timeout}")
    private static long time;
    //签名
    private static String signature = "csist";

    public static String createToken(){
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                /*header*/
                .setHeaderParam("typ","JWT")
                .setHeaderParam("alg","HS256")
                /*payload*/
                .claim("username","admin")
                .claim("role","admin")
                .setSubject("admin-test")
                .setExpiration(new Date(System.currentTimeMillis()+time))
                .setId(UUID.randomUUID().toString())
                /*signature*/
                .signWith(SignatureAlgorithm.HS256,signature)
                .compact();
        return jwtToken;
    }

    public static boolean checkToken(String token){
        if (token==null||token.trim().equals("")){
            return false;
        }
        try {
            Jws<Claims> jws = Jwts.parser().setSigningKey(signature).parseClaimsJws(token);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
